from .models import PListModel
from rest_framework import serializers
from dateutil.relativedelta import relativedelta
import datetime

class PListCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = PListModel
        fields = '__all__'



class PListSerializer(serializers.ModelSerializer):
    date = serializers.SerializerMethodField()

    def get_date(self, obj):
        birth_date_str = obj.date

        birth_date = datetime.datetime.strptime(birth_date_str, '%Y-%m-%d')
        current_date = datetime.datetime.now()

        # 使用relativedelta计算年龄差值
        diff = relativedelta(current_date, birth_date)
        if diff.years == 0:
            return f"{diff.months}月{diff.days}天"
        if diff.years < 2:
            return f"{diff.months + 12 }月{diff.days}天"
        if 2 <= diff.years < 7:
            return f"{diff.years}年{diff.months}月"
        if diff.years >= 7:
            return f"{diff.years}岁"


    class Meta:
        model = PListModel
        fields = ['id','name','sex','date','weight','allergic','history','get_liver_display',
                  'get_kidney_display','get_gestation_display','select']



































